package com.ltmall.api.dao.impl;

import com.ltmall.api.bean.DirectorPrivilegeOrder;
import com.ltmall.api.bean.ThSubUnderwritingIncomes;
import com.ltmall.api.dao.IDirectorPrivilegeOrderDAO;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import static com.ltmall.api.util.HibernateUtil.closeSession;
import static com.ltmall.api.util.HibernateUtil.getSession;

public class DirectorPrivilegeOrderDAO extends HibernateDaoSupport implements IDirectorPrivilegeOrderDAO {

	@Override
	public int countPurchasedTimes(int packageId, int userId) {
		final String SQL = "SELECT * FROM flavor_director_privilege_order WHERE director_privilege_package_id = ? and user_id = ? and pay = 1";
		Session session = getSession();
		Query query = session.createSQLQuery(SQL).addEntity(DirectorPrivilegeOrder.class);
		query.setParameter(0, packageId);
		query.setParameter(1, userId);
		return query.list().size();
	}

	@Override
	public boolean save(DirectorPrivilegeOrder directorPrivilegeOrder) {
		Session session = getSession();
		try {
			session.saveOrUpdate(directorPrivilegeOrder);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			// releaseSession(session);
			closeSession();
		}
	}

	@Override
	public DirectorPrivilegeOrder getByTradeNo(String tradeNo) {
		final String SQL = "SELECT * FROM flavor_director_privilege_order WHERE transaction_number = ?";
		Session session = getSession();
		Query query = session.createSQLQuery(SQL).addEntity(DirectorPrivilegeOrder.class);
		query.setParameter(0, tradeNo);
		DirectorPrivilegeOrder order = (DirectorPrivilegeOrder) query.list().get(0);
		return order;
	}

	@Override
	public boolean saveThSubUnderwritingIncomes(ThSubUnderwritingIncomes income) {
		Session session = getSession();
		try {
			session.saveOrUpdate(income);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			// releaseSession(session);
			closeSession();
		}
	}

	@Override
	public boolean addSubUnderwriterTotalIncome(int underwriterId, double amount) {
		final String SQL = "UPDATE th_sub_underwriters SET total_income = total_income + ? WHERE id = ?";
		Session session = getSession();
		Query query = session.createSQLQuery(SQL);
		query.setParameter(0, amount);
		query.setParameter(1, underwriterId);
		int affectedRows = query.executeUpdate();
		return affectedRows != 0;
	}
}
